# from threading import Thread,Lock
# n=0
# def add(lock):
#     for i in range(500000):
#         global n
#         with lock:
#             n+=1
#
# def sub(lock):
#     for i in range(500000):
#         global n
#         with lock:
#             n-=1
#
# t_l=[]
# lock=Lock()
# for i in range(2):
#     t1=Thread(target=add,args=(lock,))
#     t1.start()
#     t2=Thread(target=sub,args=(lock,))
#     t2.start()
#     t_l.append(t1)
#     t_l.append(t2)
# for t in t_l:t.join()
# print(n)

from threading import Thread,Lock
import time
n = []
def append():
    for i in range(500000):
        n.append(1)
def pop(lock):
    for i in range(500000):
        with lock:
            if not n:#判断后再pop数据不安全
                time.sleep(0.0000001)    # 强制CPU轮转
        n.pop()
t_l = []
lock = Lock()
for i in range(20):
    t1 = Thread(target=append)
    t1.start()
    t2 = Thread(target=pop,args=(lock,))
    t2.start()
    t_l.append(t1)
    t_l.append(t2)
for t in t_l:
    t.join()
print(n,len(n))



















